package com.springmvc.demo.config;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.springmvc.demo.model.User;
import com.springmvc.demo.model.UserRole;
import com.springmvc.demo.service.UserService;



public class MyRealm extends AuthorizingRealm{
	@Autowired
	UserService userServiceImpl;
	
	
	
	private final static Logger logger = LogManager.getLogger(MyRealm.class);
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		
		logger.debug("##################执行Shiro权限认证##################");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		User user=(User) principals.getPrimaryPrincipal();
		 if(user!=null){
	            //SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	            //注入角色
	            List<UserRole> list=userServiceImpl.checkUserHasRoles(user.getUserid());
	            for(UserRole ur:list) {
	            	info.addRole(ur.getRoleid());
	            }
	            // TODO 注入权限
	            /*
	             * 
	            List<RolePermission> list=userServiceImpl.checkUserHasRoles(user.getUserid());
	            for(UserRole ur:list) {
	            	info.addRole(ur.getRoleid());
	            }
	             * 
	             * */

	            return info;
	        }
		
		
		 return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (String) token.getPrincipal();
		//String password = (String) token.getCredentials();
		String password = new String((char[]) token.getCredentials());
		User user=userServiceImpl.getUserByUserid(username);
		 if(null == user){
	            throw new UnknownAccountException();
	        }else {
	            if(password.equals(user.getPwd())){

	                    SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(user,user.getPwd(),getName());
	                    return authorizationInfo;
	                
	            } else {
	                throw new IncorrectCredentialsException();
	            }
	        }
		 
		
		
	}

}
